package edu.pku.sei.transformation.constraint;

import java.util.ArrayList;

import org.eclipse.jface.action.Action;

import edu.pku.sei.transformation.editor.model.constraint.Constraint;
import edu.pku.sei.transformation.editor.model.constraint.ConstraintConnection;
import edu.pku.sei.transformation.editor.model.execution.Model;
import edu.pku.sei.transformation.editor.model.test.CheckPoint;
import edu.pku.sei.transformation.editor.model.test.CheckPointOperand;
import edu.pku.sei.transformation.editor.views.console.ConsoleViewManager;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;

public class CheckConstraintAction extends Action{
	CheckPoint checkPoint = null;
	ConstraintEngine engine = null;
	ArrayList<Constraint> exps = new ArrayList<Constraint>();
	Model model = null;
	
	public CheckConstraintAction(CheckPoint p, ConstraintEngine engine) {
		this.setText(engine.getEngineName());
		this.setImageDescriptor(IconsProvider.getImageDescriptor(IconsProvider.CHECKPOINT_ICO));
		this.checkPoint = p;
		this.engine = engine;
	}
	
	@Override
	public boolean isEnabled() {
		if(checkPoint == null || engine == null)
			return false;
		else
			return super.isEnabled();
	}
	
	@Override
	public void run() {
		if (checkPoint == null)
			return;
		for (ConstraintConnection connection : checkPoint.getConstraintConnections()) {
			Constraint c = connection.getConstraint();
			if (Constraint.LANGUAGE_OCL.equals(c.getLanguage())) {
				exps.add(c);
			}
		}
		for (CheckPointOperand operand : checkPoint.getOperands()) {
			if (operand.getOperand() instanceof Model) {
				this.model = (Model) operand.getOperand();
			}
		}
		if ( model == null) {
			return;
		}
		
		String metaModelPath = model.getMetaModel().getFilePath();
		String modelPath = model.getFile();
		boolean result;
		if (engine.init(metaModelPath, modelPath)) {
			for (Constraint exp : exps) {
					result = engine.checkConstraint(exp.getContent());
					if (result)
						exp.setCheckState(Constraint.STATE_SUCCESS);
					else
						exp.setCheckState(Constraint.STATE_FAIL);
			}
		}	
	}
}
